package com.lanswon.qzsmk.business.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lanswon.qzsmk.base.AccountContants;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.business.EPLoadBusiness;
import com.lanswon.qzsmk.dao.AccTxnDtlMapper;
import com.lanswon.qzsmk.dao.AppKindMapper;
import com.lanswon.qzsmk.dao.BusinessMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CardTypeMapper;
import com.lanswon.qzsmk.dao.CenterSerialNumberMapper;
import com.lanswon.qzsmk.dao.CertMapper;
import com.lanswon.qzsmk.dao.CrdTxnTacRecMapper;
import com.lanswon.qzsmk.dao.OnlTmpMapper;
import com.lanswon.qzsmk.dao.PersonalMapper;
import com.lanswon.qzsmk.dao.SubaccountPersonalMapper;
import com.lanswon.qzsmk.dao.TransGlideMapper;
import com.lanswon.qzsmk.dao.TxnDtlMapper;
import com.lanswon.qzsmk.dao.TxnHisDtlMapper;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.AppKind;
import com.lanswon.qzsmk.model.Business;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.CenterSerialNumber;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.model.CrdTxnTacRec;
import com.lanswon.qzsmk.model.OnlTmp;
import com.lanswon.qzsmk.model.Personal;
import com.lanswon.qzsmk.model.SubaccountPersonal;
import com.lanswon.qzsmk.model.TransGlide;
import com.lanswon.qzsmk.model.TxnDtl;
import com.lanswon.qzsmk.util.ConnectionPoolUtil;
import com.lanswon.qzsmk.util.CopyBean;
import com.lanswon.qzsmk.util.SequenceNumberUtil;
import com.lanswon.qzsmk.vo.BussinessVo;
import com.lanswon.qzsmk.vo.RechargeCancelVo;
import com.lanswon.qzsmk.vo.VoucherVo;
import com.lanswon.smk.common.kmsserror.KmssException;
import com.lanswon.smk.kmssclient.connection.ConnectionPool;
import com.lanswon.smk.kmssclient.connection.KmssConnection;
import com.lanswon.smk.kmssclient.vo.KmssMac2ReqVO;
import com.lanswon.smk.kmssclient.vo.KmssMac2RespVO;
import com.lanswon.smk.kmssclient.vo.KmssTacReqVO;
import com.lanswon.smk.kmssclient.vo.KmssTacRespVO;

/**
 * 圈存业务
 * 
 * @author guyawei
 *
 */
@Service
public class EPLoad implements EPLoadBusiness {

	@Autowired
	CrdTxnTacRecMapper cttrm;

	@Autowired
	CardDataMapper cdm;

	@Autowired
	AccTxnDtlMapper am;

	@Autowired
	OnlTmpMapper otm;

	@Autowired
	CenterSerialNumberMapper csnm;

	@Autowired
	CardControlMapper ccm;

	@Autowired
	PersonalMapper pm;

	@Autowired
	CertMapper cm;

	@Autowired
	BusinessMapper bm;

	@Autowired
	CardTypeMapper ctm;

	@Autowired
	SubaccountPersonalMapper spm;

	@Autowired
	AppKindMapper akm;

	@Autowired
	TransGlideMapper tgm;

	@Autowired
	TxnHisDtlMapper thdm;

	@Autowired
	TxnDtlMapper tdm;


	@Override
	public String generateCenterSerialNumber(CenterSerialNumber csn) {
		// String centerSerialNumber = "";
		// String cityCode = "";
		// String date = "";
		// Date d = new Date();
		// int seq = 0;
		// if (csn == null) {
		// cityCode = CardContants.CITY_CODE;
		// seq = 1;
		// } else {
		// cityCode = csn.getCityCode();
		// date = DateFormatUtils.format(csn.getDate(), "yyyyMMdd");
		// if (CommonUtil.checkDate(d)) {
		// seq = csn.getSequence() + 1;
		// } else {
		// seq = 1;
		// }
		//
		// }
		// int length = 10 - String.valueOf(seq).length();
		// String prefix = "";
		// for (int i = 0; i < length; i++) {
		// prefix += 0;
		// }
		// String seqNo = prefix + String.valueOf(seq);
		//
		// centerSerialNumber = cityCode + date + seqNo;
		// CenterSerialNumber cc = new CenterSerialNumber();
		// cc.setCityCode(cityCode);
		// cc.setDate(d);
		// cc.setSequence(seq);
		// csnm.insert(cc);
		// return centerSerialNumber;
		return "";
	}

	@Override
	public Map<String, Object> loadRequest(BussinessVo bv) throws Exception, KmssException {
		Map<String, Object> map = new HashMap<>();
		String content = null;
		KmssMac2RespVO resp = checkMac(bv);
		System.out.println(resp.isbMacRs() + ";" + resp.gethMac2());
		boolean flag = resp.isbMacRs();
		int statusCode=200;
		if (!flag) {
			// mac1效验失败
			statusCode=300;
			content = resp.getsErrorInfo() + "圈存请求失败";
		} else {
			// mac1效验成功，获取mac2
			content = resp.gethMac2();
		}
		map.put("statusCode", statusCode);
		map.put("message", content);
		return map;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public Map<String, Object> load(BussinessVo bv) throws Exception, KmssException {
		ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		if (activeUser == null) {
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}

		Map<String, Object> map = new HashMap<>();
		Date now = new Date();
		String citizenCardNo = bv.getCitizenCardNo();
		SubaccountPersonal sp = spm.querySubaccountPersonalByAppFlagAndWallet(bv.getAppFlag(), citizenCardNo,
				bv.getWalletType());
		// 上一次临时交易记录
		OnlTmp lastOt = otm.queryLastOnlTmp(citizenCardNo);
		
		
		// 卡钱包
		SubaccountPersonal cardWallet = spm.querySubaccountPersonalByAppFlagAndWallet(bv.getAppFlag(),citizenCardNo, bv.getWalletType());
		
		//账户当前余额
		BigDecimal totalBalance=cardWallet.getTotalBalance();
		//临时表
		OnlTmp ot = new OnlTmp();

		ot = (OnlTmp) CopyBean.copyA2b(bv, ot);

		// ot.setSubaccountNo(sp.getSubaccountNo());// 子帐号
		ot.setIssCityCd(CardContants.CITY_CODE);// 发卡城市代码
		ot.setTxnCityCd(CardContants.CITY_CODE);// 消费城市代码

		ot.setCrdIndustCd(String.valueOf(citizenCardNo.charAt(3)));// 卡行业代码
		String crdPhysTp = String.valueOf(citizenCardNo.charAt(2));
		ot.setCrdPhysTp(crdPhysTp);// 卡物理类型
		// CenterSerialNumber csn = csnm.queryLastOne(null);
		// String ctSeq = generateCenterSerialNumber(csn);
		// ot.setCtSeq(ctSeq);// 中心流水号
		// ot.setCtDt(csn.getDate());// 中心时间
		ot.setCashFlag(AccountContants.CASH_FLAG_COLLECT);// 现金收付标志
		ot.setTxnBalBef(totalBalance);// 交易前账户余额
		ot.setTxnBalAft(totalBalance.add(bv.getTxnAmt()));// 交易后账户余额
		ot.setCrdBalAft(bv.getCrdBalAft());
		ot.setSetDt(now);// 结算日期
		ot.setFeeTp(AccountContants.FEE_TYPE_PRINCIPAL);// 费用类型

		ot.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
		ot.setAcceptCusNo(activeUser.getBranchNo());// 受理商户/网点编号

		ot.setTxnTstFlg(AccountContants.TRANSACTION_TEST_FLAG_COMMON);// 交易测试标志

		ot.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标志

		// ot.setAdjCtSeq(adjCtSeq);//关联中心流水号
		//
		// ot.setAdjCtDt(adjCtDt);//关联中心时间
		//
		// ot.setAdjSetDt(adjSetDt);//关联结算日期
		//

		if (lastOt != null) {
			ot.setLastTxnCnt(lastOt.getCurrCount());// 上一次交易卡计数器
			ot.setLastTxnDt(DateUtils.parseDate(lastOt.getTxnDt()));// 上一次交易时间
			ot.setLastTxnAmt(lastOt.getTxnAmt());// 上一次交易金额
			ot.setCurrCount(lastOt.getCurrCount() + 1);// 当前计数器值
		} else {
			ot.setCurrCount(0);// 当前计数器值
			ot.setLastTxnCnt(0);// 上一次交易卡计数器
		}

		ot.setOprNo(activeUser.getUserNo().toString());

		ot.setCrdCityCd(CardContants.CITY_CODE);

		// ot.setBusinessNo(businessNo);// 业务编号

		otm.insert(ot);

		String content = null;
		int statusCode=200;
		KmssTacRespVO resq = checkTac(bv);
		boolean flag = resq.isbTacRs();
		System.out.println("TAC校验" + flag);
		if (!flag) {
			// tac效验失败
			content = "圈存失败" + resq.getsErrorInfo();
			statusCode=300;
		} else {
			// tac效验成功
			content = "圈存成功";

			AppKind ak = akm.queryAppKindByAppFalg(bv.getAppFlag());

			
			cardWallet.setCrdBalance(bv.getCrdBalAft());// 卡面余额
			cardWallet.setCurrCount(cardWallet.getCurrCount() + 1);// 当前计数器值
			cardWallet.setRemark("充值卡钱包");
			cardWallet.setTotalBalance(cardWallet.getTotalBalance().add(bv.getTxnAmt()));// 账面余额
			cardWallet.setTotalExchangeAmt(cardWallet.getTotalExchangeAmt().add(bv.getTxnAmt()));// 累计圈存金额
			cardWallet.setTotalExchangeCnt(cardWallet.getTotalExchangeCnt() + 1);// 累计圈存笔数
			cardWallet.setTotalReloadAmt(cardWallet.getTotalReloadAmt().add(bv.getTxnAmt()));// 累计充值金额
			cardWallet.setTotalReloadCnt(cardWallet.getTotalReloadCnt() + 1);// 累计充值笔数
			spm.update(cardWallet);
			
			Cert c = new Cert();

			CardControl cc = ccm.queryCardControlByCitizenCardNo(citizenCardNo);
			CardData cd = cdm.queryCardDataByCitizenCardNo(citizenCardNo);
			Personal p=null;
			if(!cd.getCardTypecode().equals(CardContants.CARD_TYPE_ANONYMOUS)){
				p = pm.queryPersonalByCustomerNo(cd.getCustomerNo());
			} 
			c.setCertNo(SequenceNumberUtil.generatorCertNo());
			c.setCardControlId(cc.getCardControlId());
			if(bv.getWalletType().equals(AccountContants.WALLET_TYPE_ELECTRONIC_BANKBOOK)){
				c.setCertType(CardContants.Electronic_bankbook_recharge);
			}else if(bv.getWalletType().equals(AccountContants.WALLET_TYPE_ELECTRONIC_WALLET)){
				c.setCertType(CardContants.ELECTRONIC_PURSE_RECHARGE);
			}
			c.setCardpCode(cd.getCardpCode());
			c.setCardTypecode(cd.getCardTypecode());
			if(p!=null){
				c.setName(p.getCustomerName());
				c.setPaperType(p.getPaperType());
				c.setPaperNo(p.getPaperNo());
			}		
			// c.setStatus(status);
			c.setData("充值");
			c.setBranchNo(activeUser.getBranchNo());
			c.setCrtOperator(activeUser.getUserNo().toString());
			c.setCrtDate(now);
			c.setLastOperator(activeUser.getUserNo().toString());
			c.setLastDate(now);
			c.setBranch(activeUser.getBranchName());
			
			
			Business b = new Business();
			b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
			b.setCardControlId(cc.getCardControlId());
			b.setCustomerNo(p==null?"":p.getCustomerNo());
			b.setCardpCode(cd.getCardpCode());
			b.setTellerNo(activeUser.getUserNo().toString());
			b.setTransDate(now);
			b.setSeqStatus(CardContants.LSZT_NORMAL);
			b.setCertNo(c.getCertNo());
			bm.insert(b);
			
			c.setBusinessNo(b.getBusinessNo());
			cm.insert(c);

			// 当日交易明细
			TxnDtl td = new TxnDtl();
//			td. setCrdNo("") ;
//			td. setCardSeqNo(""); 
//			td. setCrdUniqueNo("");
			td. setCitizenCardNo(citizenCardNo);
//			td. setSubaccountNo(String subaccountNo);
			td. setIssCityCd("2625");		
			td. setTxnCityCd("2625") ;
//			td. setCrdIndustCd(String crdIndustCd);//卡行业代码
			td. setAppFlag(bv.getAppFlag());
//			td. setCrdPhysTp(String crdPhysTp) ;//卡物理类型 		  
//			td.setCtSeq(String ctSeq);//中心流水号 			   
//			td. setCtDt(Date ctDt) ;//中心时间
			td. setCashFlag(AccountContants.CASH_FLAG_COLLECT); //现金收付标志 0.无,1.收取 2.支出,3.收支
			td. setTxnTp(bv.getCrdTxnType());//	卡交易类型
			td. setTxnDt(bv.getTxnDt());			   
			td. setTxnBalBef(totalBalance) ;//账户交易前余额		 
			td. setTxnBalAft(cardWallet.getTotalBalance());			    
			td. setTxnAmt(bv.getTxnAmt()) ;			  
			td. setCrdBalBef(bv.getCrdBalBef()) ;//卡交易前 余额
			td.setCrdBalAft(bv.getCrdBalAft()) ;
//			td. setSetDt(Date setDt);//结算日期			   
			td. setFeeTp(AccountContants.FEE_TYPE_PRINCIPAL);//费用类型  0.本金 1:工本费 2.交易手续费 3:租金4:押金			    
//			td. setAcceptTp("06");//受理类型 表示终端的归属，由上传的终端代码决定：01-网点 06-商户
		    td. setAcceptCusNo(activeUser.getBranchNo()) ;//受理商户/网点编号			  
//		    td. setTermNo("");//终端代码			    
//			td. setTermSeq(String termSeq) ;//终端流水号			   
		    td.setSamNo(bv.getSamNo());//			  
//			td. setSamSeq(String samSeq) ;			    
//			td. setTxnFileName("");//交易文件名称
//			td. setPkgRecOrd(Integer pkgRecOrd) ;//所属数据包记录序号 
		    td. setDivFactor(bv.getDivFactor());
		    td.setTxnTac(bv.getTxnTac());
//		    td. setTxnCharcFld(String txnCharcFld) ;//交易个性域
		    td. setTxnTstFlg("0") ;//交易测试标志 "0"-普通; "1"-测试			   
//		    td. setErrCode(String errCode);//错误代码 记录级错误			    
		    td. setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);//交易流水标志 "00" 正常 "41" 撤销			   
//		    td.setAdjCtSeq(String adjCtSeq) ;//关联中心流水号			    
//		    td. setAdjCtDt(Date adjCtDt);//关联中心时间
//		    td.setTxnMac1(String txnMac1) ;
//		    td.setTxnMac2(String txnMac2);			  
//		    td.setAdjSetDt(Date adjSetDt) ;//关联结算日期			   
//		    td. setLastTxnCnt(cardWallet.getTotalReloadCnt()) ;//上一次交易卡计数器			   
//		    td. setLastTxnDt(Date lastTxnDt) ;//上一次交易时间			 
//		    td. setLastTxnAmt(BigDecimal lastTxnAmt) ;//上一次交易金额			   
//		    td. setCurrCount(Integer currCount);//当前计数器值 		   
		    td. setWarrantid(c.getCertNo()) ;//凭证号
//		    td.setOutWarrantid(String outWarrantid);//外部凭证号			   
		    td. setOprNo(activeUser.getUserNo().toString());//操作员编号/终端操作员编号 			  
//		    td. setLocalTxnSeq(String localTxnSeq);//本地流水号			    
		    td. setTxnAttr(AccountContants.TXNTP_RECHARGE) ;//交易性质 			   
//		    td. setStationId(String stationId) ;//采集点编号
//		    td. setPosCarrId(String posCarrId);//POS机载体编号
		    td. setCrdCityCd("2625");//卡城市代码
		    td. setCardType(cd.getCardTypecode());
		    td. setRsvdFlags(AccountContants.TXNTP_RECHARGE);	//预留标志组		   
//		    td. setRsvdFld(String rsvdFld);//保留字段
//		    td. setReserve1(String reserve1) ;			   
//		    td. setReserve2(String reserve2);
//		    td. setReserve3(String reserve3);
//		    td. setReserve4(String reserve4);			  
//		    td. setReserve5(String reserve5) ;
//		    td. setReserve6(String reserve6) ;
//		    td. setReserve7(String reserve7) ;
//		    td.setReserve8(String reserve8) ;
//		    td. setReserve9(String reserve9) ;
//		    td.setReserve10(String reserve10) ;
//		    td.setFileGenDate(Date fileGenDate) ;//文件生成日期 
		    if(bv.getAppFlag().equals("3F01")){
		    	td.setTxnType(AccountContants.TRADE_TYPE_BUS) ;//终端交易类型 
		    } 
		    td.setTxnDate(bv.getTxnDt().substring(0,8)) ;	//交易日期		   
//		    td.setOutEntityno(String outEntityno);//外部实体编号
		    td. setBusinessNo(b.getBusinessNo());//
		    td. setPaymentType("0");//支付方式  0 现金 1 兑换券  默认为0
		    td.setPaymentTypeExt("0");//支付方式是否扩展 0 否1 是  默认为0
		    td.setRealTxnAmt(bv.getTxnAmt());
		    tdm.insert(td);

			// 交易明细流水表
			TransGlide tg = new TransGlide();
			tg.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
			tg.setAccountType(bv.getWalletType());// 账户类型
			// tg.setAllowReturn(AccountContants.STATUS_INVALID);//不可退费
			tg.setAppFlag(bv.getAppFlag());// 应用标识
			tg.setAppType(bv.getAppType());// 应用类型
			tg.setBranchNo(activeUser.getBranchNo());
			 tg.setBusinessNo(b.getBusinessNo());//业务流水号
			tg.setCitizenCardNo(bv.getCitizenCardNo());// 市民卡号
			tg.setCashFlag(AccountContants.CASH_FLAG_COLLECT);// 现金收付标志
			// tg.setFeeRuleId(feeRuleId);//卡费用规则ID
			// tg.setFeeRulesId(feeRulesId);//卡费用细则ID
			tg.setFeeTp(AccountContants.FEE_TYPE_PRINCIPAL);// 费用类型
			// tg.setIsReturned(AccountContants.STATUS_VALID);//是否已退费
			tg.setOprNo(activeUser.getUserNo().toString());
			tg.setPaymentType(AccountContants.PAYMENT_TYPE_CASH);// 现金

			tg.setPaymentTypeExt(AccountContants.STATUS_INVALID);
			// tg.setRptDate(rptDate);//轧帐日期
			tg.setRptFlag(AccountContants.RPT_FLAG_NO);// 轧帐标识 0未过账
			// tg.setSubaccountNo(subaccountNo);//网点子账号
			// tg.setReturnTransGlideId(returnTransGlideId);//退费交易明细流水ID
			tg.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标识
			tg.setTxnAmt(bv.getTxnAmt());// 交易金额
			tg.setTxnDt(now);// 交易时间
			tg.setTxnTp(AccountContants.TXNTP_RECHARGE);// txnTp 交易类型

			tgm.insert(tg);
			Calendar cal = Calendar.getInstance();

			
			
			c.setBusinessNo(b.getBusinessNo());
			cm.update(c);

			ot.setBusinessNo(b.getBusinessNo());
			otm.update(ot);
			
			String str = "{\"title\":\""+"充值凭证"+"\",\"type\":\""+"EPPay"+"\",\"certNo\":\""+c.getCertNo()+"\",\"busType\":\""
			+CardContants.getCertTypeNameByCode(c.getCertType())+"\",\"cardType\":\""+c.getCardTypecode()+"\",\"citizenCardNo\":\""
			+bv.getCitizenCardNo()+"\",\"crdBalBef\":\""+bv.getCrdBalBef()+"\",\"txnAmt\":\""+bv.getTxnAmt()+"\",\"crdBalAft\":\""
			+bv.getCrdBalAft()+"\",\"net\":\""+activeUser.getBranchName()+"\",\"appFlag\":\""+bv.getAppFlag()+"\",\"operator\":\""
			+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")+"\"}";
			c.setData(str);
			c.setTransCode("充值");
			cm.update(c);

			VoucherVo vo = new VoucherVo();
			vo.setCertNo(c.getCertNo());
			vo.setCardType(ctm.queryCardTypeByCode(cd.getCardTypecode()).getCardTypeCode());
			vo.setNewCitizenCardNo(bv.getCitizenCardNo());
			vo.setBusinessTypeName(CardContants.getCertTypeNameByCode(CardContants.ELECTRONIC_PURSE_RECHARGE));
			vo.setAriginalAmount(bv.getCrdBalBef().toString());
			vo.setTransactionAmount(bv.getTxnAmt().toString());
			vo.setCurrentAmount((bv.getCrdBalAft()).toString());
			vo.setAppFlag(bv.getAppFlag());
			vo.setOperator(activeUser.getUserNo().toString());
			vo.setNet(activeUser.getBranchName());
			vo.setTransactionDate(DateFormatUtils.format(now, "yyyy-MM-dd HH:mm:ss"));
			map.put("VoucherVo", vo);
		}
		map.put("statusCode", statusCode);
		map.put("message", content);

		return map;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public Map<String, Object> checkTacByRechargeCancel(RechargeCancelVo rv) throws Exception, KmssException {
		ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		if (activeUser == null) {
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}

		Cert cert=cm.queryPreviousCertByCitizenCardNo(rv.getCitizenCardNo());
		if(!(cert.getCertType().equals(CardContants.ELECTRONIC_PURSE_RECHARGE))&&!(cert.getCertType().equals(CardContants.Electronic_bankbook_recharge))){
			throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "充值后已办理其他业务，无法撤销");
		}
		
		Date now = new Date();

		Map<String, Object> map = new HashMap<>();
		boolean flag = true;
		//KmssTacRespVO resp = checkTac(rv);
		
		//flag = resp.isbTacRs();
		
		System.out.println("充值撤销tac校验"+flag);
		
//		  String content = null; 
//		  if (flag){ 
//			  content = "充值撤销效验成功"; 
//		  } 
//		  else {
//			  content = "充值撤销效验失败" + resp.getsErrorInfo();
//		  }
		  
		 
		// 卡钱包
		
		SubaccountPersonal cardWallet = spm.querySubaccountPersonalByAppFlagAndWallet(rv.getAppFlag(),
				rv.getCitizenCardNo(), rv.getWalletType());
		
		
		//账户当前余额
		BigDecimal totalBalance=cardWallet.getTotalBalance();
		
//		cardWallet.setTotalBalance(cardWallet.getTotalBalance().subtract(rv.getTxnAmt()));// 账面余额
//		cardWallet.setCrdBalance(totalBalance.subtract(rv.getTxnAmt()));// 卡余额

//		spm.update(cardWallet);
		
		CardData cd = cdm.queryCardDataByCitizenCardNo(rv.getCitizenCardNo());
		// 产生消费记录
		// 当日交易明细
		TxnDtl td = new TxnDtl();
		td. setCrdNo("") ;
//		td. setCardSeqNo(""); 
//		td. setCrdUniqueNo("");
		td. setCitizenCardNo(rv.getCitizenCardNo());
//		td. setSubaccountNo(String subaccountNo);
		td. setIssCityCd("2625");		
		td. setTxnCityCd("2625") ;
//		td. setCrdIndustCd(String crdIndustCd);//卡行业代码
		td. setAppFlag(rv.getAppFlag());
//		td. setCrdPhysTp(String crdPhysTp) ;//卡物理类型 		  
//		td.setCtSeq(String ctSeq);//中心流水号 			   
//		td. setCtDt(Date ctDt) ;//中心时间
		td. setCashFlag(AccountContants.CASH_FLAG_NOTHING); //现金收付标志 0.无,1.收取 2.支出,3.收支
		td. setTxnTp(rv.getCrdTxnType());//	   
		td. setTxnDt(rv.getTxnDt());			   
		td. setTxnBalBef(totalBalance) ;		 
		td. setTxnBalAft(cardWallet.getTotalBalance());			    
		td. setTxnAmt(rv.getTxnAmt()) ;			  
		td. setCrdBalBef(rv.getCrdBalBef()) ;
		td.setCrdBalAft(rv.getCrdBalAft()) ;
//		td. setSetDt(Date setDt);//结算日期			   
		td. setFeeTp(AccountContants.FEE_TYPE_PRINCIPAL);//费用类型  0.本金 1:工本费 2.交易手续费 3:租金4:押金			    
		td. setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);//受理类型 表示终端的归属，由上传的终端代码决定：01-网点 06-商户
	    td. setAcceptCusNo(activeUser.getBranchNo()) ;//受理商户/网点编号			  
//	    td. setTermNo("");//终端代码			    
//		td. setTermSeq(String termSeq) ;//终端流水号			   
	    td.setSamNo(rv.getSamNo());//			  
//		td. setSamSeq(String samSeq) ;			    
//		td. setTxnFileName("");//交易文件名称
//		td. setPkgRecOrd(Integer pkgRecOrd) ;//所属数据包记录序号 
	    td. setDivFactor(rv.getDivFactor());
	    td.setTxnTac(rv.getTxnTac());
//	    td. setTxnCharcFld(String txnCharcFld) ;//交易个性域
	    td. setTxnTstFlg("0") ;//交易测试标志 "0"-普通; "1"-测试			   
//	    td. setErrCode(String errCode);//错误代码 记录级错误			    
	    td. setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);//交易流水标志 "00" 正常 "41" 撤销			   
//	    td.setAdjCtSeq(String adjCtSeq) ;//关联中心流水号			    
//	    td. setAdjCtDt(Date adjCtDt);//关联中心时间
	    td.setTxnMac1(rv.getTxnMac1()) ;
	    td.setTxnMac2(rv.getTxnMac2());			  
//	    td.setAdjSetDt(Date adjSetDt) ;//关联结算日期			   
//	    td. setLastTxnCnt(cardWallet.getTotalReloadCnt()) ;//上一次交易卡计数器			   
//	    td. setLastTxnDt(Date lastTxnDt) ;//上一次交易时间			 
//	    td. setLastTxnAmt(BigDecimal lastTxnAmt) ;//上一次交易金额			   
//	    td. setCurrCount(Integer currCount);//当前计数器值 		   
//	    td. setWarrantid(c.getCertNo()) ;//凭证号
//	    td.setOutWarrantid(String outWarrantid);//外部凭证号			   
	    td. setOprNo(activeUser.getUserNo().toString());//操作员编号/终端操作员编号 			  
//	    td. setLocalTxnSeq(String localTxnSeq);//本地流水号			    
	    td. setTxnAttr(AccountContants.TXNTP_CONSUMPTION) ;//交易性质 			   
//	    td. setStationId(String stationId) ;//采集点编号
//	    td. setPosCarrId(String posCarrId);//POS机载体编号
	    td. setCrdCityCd("2625");//卡城市代码
	    td. setCardType(cd.getCardTypecode());
	    td. setRsvdFlags(AccountContants.TXNTP_CONSUMPTION);	//预留标志组   ---清结算修改		   
//	    td. setRsvdFld(String rsvdFld);//保留字段
//	    td. setReserve1(String reserve1) ;			   
//	    td. setReserve2(String reserve2);
//	    td. setReserve3(String reserve3);
//	    td. setReserve4(String reserve4);			  
//	    td. setReserve5(String reserve5) ;
//	    td. setReserve6(String reserve6) ;
//	    td. setReserve7(String reserve7) ;
//	    td.setReserve8(String reserve8) ;
//	    td. setReserve9(String reserve9) ;
//	    td.setReserve10(String reserve10) ;
//	    td.setFileGenDate(Date fileGenDate) ;//文件生成日期 
	    if(rv.getAppFlag().equals("3F01")){
	    	td.setTxnType(AccountContants.TRADE_TYPE_BUS) ;//行业交易类型 
	    } 
	    td.setTxnDate(rv.getTxnDt().substring(0,8)) ;	//交易日期		   
//	    td.setOutEntityno(String outEntityno);//外部实体编号
//	    td. setBusinessNo(b.getBusinessNo());//
//	    td. setPaymentType("0");//支付方式  0 现金 1 兑换券  默认为0
	    td.setPaymentTypeExt("0");//支付方式是否扩展 0 否1 是  默认为0
	    td.setRealTxnAmt(rv.getTxnAmt());
	    tdm.insert(td);

		//交易明细流水表
		TransGlide tg = new TransGlide();
		tg.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
		tg.setAccountType(rv.getWalletType());// 账户类型
		// tg.setAllowReturn(AccountContants.STATUS_INVALID);//不可退费
		tg.setAppFlag(rv.getAppFlag());// 应用标识
		tg.setAppType(rv.getAppType());// 应用类型
		tg.setBranchNo(activeUser.getBranchNo());
		// tg.setBusinessNo(businessNo);//业务流水号
		tg.setCitizenCardNo(rv.getCitizenCardNo());// 市民卡号
		// tg.setCashFlag(AccountContants.CASH_FLAG_COLLECT);//现金收付标志
		// tg.setFeeRuleId(feeRuleId);//卡费用规则ID
		// tg.setFeeRulesId(feeRulesId);//卡费用细则ID
		tg.setFeeTp(AccountContants.FEE_TYPE_PRINCIPAL);// 费用类型
		// tg.setIsReturned(AccountContants.STATUS_VALID);//是否已退费
		tg.setOprNo(activeUser.getUserNo().toString());
		// tg.setPaymentType(AccountContants.PAYMENT_TYPE_CASH);//现金

		tg.setPaymentTypeExt(AccountContants.STATUS_INVALID);
		// tg.setRptDate(rptDate);//轧帐日期
		tg.setRptFlag(AccountContants.RPT_FLAG_NO);// 轧帐标识 0未过账
		// tg.setSubaccountNo(subaccountNo);//网点子账号
		// tg.setReturnTransGlideId(returnTransGlideId);//退费交易明细流水ID
		tg.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标识
		tg.setTxnAmt(rv.getTxnAmt());// 交易金额
		tg.setTxnDt(now);// 交易时间
		tg.setTxnTp(AccountContants.TXNTP_CONSUMPTION);// txnTp 交易类型

		tgm.insert(tg);
		
		
		
		Calendar cal = Calendar.getInstance();

		map.put("flag", flag);
		// map.put("content", content);
		return map;
	}

	@Override
	public KmssTacRespVO checkTac(BussinessVo bv) throws Exception, KmssException {
		ConnectionPoolUtil.getInstance();
		ConnectionPool connection = ConnectionPoolUtil.connPool;
		KmssConnection kmssConnection = connection.getConnection();
		KmssTacReqVO req = ConnectionPoolUtil.getInstanceTac(bv);
		KmssTacRespVO resp = kmssConnection.sendTacVerifyMessage(req, bv.getTxnTac());
		connection.returnConnection(kmssConnection);
		// 卡交易验证信息记录
		CrdTxnTacRec c = new CrdTxnTacRec();
		c = (CrdTxnTacRec) CopyBean.copyA2b(bv, c);
		c.setCrdBalAft(bv.getCrdBalBef());
		c.setIssCityCd(CardContants.CITY_CODE);
		c.setCardType(cdm.queryCardDataByCitizenCardNo(bv.getCitizenCardNo()).getCardTypecode());
		cttrm.insert(c);

		return resp;
	}

	@Override
	public KmssMac2RespVO checkMac(BussinessVo bv) throws Exception, KmssException {
		ConnectionPoolUtil.getInstance();
		ConnectionPool connection = ConnectionPoolUtil.connPool;
		KmssConnection kmssConnection = connection.getConnection();
		KmssMac2ReqVO req = ConnectionPoolUtil.getInstanceMac(bv);
		KmssMac2RespVO resp = kmssConnection.sendLoadMacMessage(req);
		connection.returnConnection(kmssConnection);
		return resp;
	}

	@Override
	public KmssTacRespVO checkTac(RechargeCancelVo rv) throws Exception, KmssException {
		ConnectionPoolUtil.getInstance();
		ConnectionPool connection = ConnectionPoolUtil.connPool;
		KmssConnection kmssConnection = connection.getConnection();
		KmssTacReqVO req = ConnectionPoolUtil.getInstanceTac(rv);
		KmssTacRespVO resp = kmssConnection.sendTacVerifyMessage(req, rv.getTxnTac());
		connection.returnConnection(kmssConnection);
		return resp;
	}
}
